﻿using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace Wsp365.Anonymous.ModerationEventReceiver
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class ModerationEventReceiver : SPItemEventReceiver
    {
        public static readonly string PropertyName = "Wsp365.Moderation";
        public static readonly string Enabled = "1";
        public override void ItemAdded(SPItemEventProperties properties)
        {
            base.ItemAdded(properties);
            if (string.IsNullOrEmpty(properties.UserLoginName)
                && properties.List != null
                && properties.List.RootFolder != null
                && properties.List.RootFolder.Properties.ContainsKey(PropertyName)
                && Enabled.Equals(properties.List.RootFolder.Properties[PropertyName]))
            {
                EventFiringEnabled = false;
                properties.ListItem.BreakRoleInheritance(true);
                EventFiringEnabled = true;
            }
        }

        /// <summary>
        /// An item was updated
        /// </summary>
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            if (properties.List != null
                && properties.List.RootFolder != null                
                && properties.List.RootFolder.Properties.ContainsKey(PropertyName)
                && Enabled.Equals(properties.List.RootFolder.Properties[PropertyName]))
            {
                base.ItemUpdated(properties);
                EventFiringEnabled = false;
                if (string.IsNullOrEmpty(properties.UserLoginName))
                {
                    //Reset access for anonymous users
                    properties.ListItem.BreakRoleInheritance(true);                
                }
                else
                {
                    //Test if someone has approved and reset inheirtance
                    if (properties.ListItem.ModerationInformation.Status == SPModerationStatusType.Approved)
                    {                        
                        properties.ListItem.ResetRoleInheritance();                        
                    }
                }
                EventFiringEnabled = true;
            }
        }
    }
}
